﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Utils
{
    /// <summary>
    /// 字符加解密工具类
    /// </summary>
    public static class SecurityHelper
    {
      

   

        #region DES加解密
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="text">需解密的密文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string ToDesDecrypt(this string text, string key, string iv)
        {
#if NET6_0 || NET7_0
            var provider1 = DES.Create();
#else
            var provider1 = new DESCryptoServiceProvider();
#endif

            int num1 = text.Length / 2;
            byte[] buffer1 = new byte[num1];
            for (int num2 = 0; num2 < num1; num2++)
            {
                int num3 = Convert.ToInt32(text.Substring(num2 * 2, 2), 0x10);
                buffer1[num2] = (byte)num3;
            }
            provider1.Key = Encoding.ASCII.GetBytes(StringHelper.ToMD5(key).Substring(0, 8));
            provider1.IV = Encoding.ASCII.GetBytes(StringHelper. ToMD5(iv).Substring(0, 8));

            MemoryStream stream1 = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream1, provider1.CreateDecryptor(), CryptoStreamMode.Write);

            stream2.Write(buffer1, 0, buffer1.Length);
            stream2.FlushFinalBlock();
            return Encoding.Default.GetString(stream1.ToArray());
        }

        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="str">需加密的明文文本</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string ToDesEncrypt(this string str, string key, string iv)
        {
#if NET6_0 || NET7_0
            var provider1 = DES.Create();
#else
            var provider1 = new DESCryptoServiceProvider();
#endif
            byte[] buffer1 = Encoding.Default.GetBytes(str);
            string keyMD5 = StringHelper.ToMD5(key).Substring(0, 8);
            provider1.Key = Encoding.ASCII.GetBytes(StringHelper.ToMD5(key).Substring(0, 8));
            provider1.IV = Encoding.ASCII.GetBytes(StringHelper.ToMD5(iv).Substring(0, 8));
            MemoryStream stream1 = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream1, provider1.CreateEncryptor(), CryptoStreamMode.Write);
            stream2.Write(buffer1, 0, buffer1.Length);
            stream2.FlushFinalBlock();
            StringBuilder builder1 = new StringBuilder();
            foreach (byte num1 in stream1.ToArray())
            {
                builder1.AppendFormat("{0:X2}", num1);
            }
            return builder1.ToString();
        }
        #endregion
 
        #region RSA加解密
        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="encryptString">需要加密的文本</param>
        /// <param name="xmlPrivateKey">加密私钥</param>
        /// <returns>RSA公钥加密后的数据</returns>
        public static string ToRSAEncrypt(this string encryptString, string xmlPrivateKey)
        {
            string result;
            RSACryptoServiceProvider.UseMachineKeyStore = true;
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
            provider.FromXmlString(xmlPrivateKey);
            byte[] bytes = new UnicodeEncoding().GetBytes(encryptString);
            result = Convert.ToBase64String(provider.Encrypt(bytes, false));
            return result;
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="decryptString">需要解密的文本</param>
        /// <param name="xmlPublicKey">解密公钥</param>
        /// <returns>解密后的数据</returns>
        public static string ToRSADecrypt(this string decryptString, string xmlPublicKey)
        {
            string result;
            RSACryptoServiceProvider.UseMachineKeyStore = true;
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
            provider.FromXmlString(xmlPublicKey);
            byte[] rgb = Convert.FromBase64String(decryptString);
            byte[] buffer2 = provider.Decrypt(rgb, false);
            result = new UnicodeEncoding().GetString(buffer2);
            return result;
        }

        /// <summary>
        /// 生成公钥、私钥
        /// </summary>
        /// <param name="privateKey">私钥</param>
        /// <param name="publicKey">公钥</param>
        public static void CreateKey(out string privateKey, out string publicKey)
        {
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
            privateKey = provider.ToXmlString(true);
            publicKey = provider.ToXmlString(false);
        }
        #endregion

        #region AES

        /// <summary>
        /// AES 解密
        /// </summary>
        /// <param name="decryptStr"></param>
        /// <param name="AesKey"></param>
        /// <returns></returns>
        public static string AESDecrypt(string decryptStr, string AesKey)
        {
            byte[] keyArray = Encoding.UTF8.GetBytes(AesKey);
            byte[] toEncryptArray = Convert.FromBase64String(decryptStr);
#if NET6_0 
            var rDel = Aes.Create("AesManaged");
#elif  NET7_0
            var rDel = Aes.Create();
#else
            var rDel = new RijndaelManaged();
#endif
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }

        /// <summary>
        /// ASE 加密 ECB
        /// </summary> 
        /// <returns></returns>
        public static string AESEncrypt(string encryptStr, string AesKey)
        {
            byte[] keyArray = Encoding.UTF8.GetBytes(AesKey);
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(encryptStr);
#if NET6_0 
            var rDel = Aes.Create("AesManaged");
#elif  NET7_0
            var rDel = Aes.Create();
#else
            var rDel = new RijndaelManaged();
#endif
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        #endregion

        public static string Sha1Sign(string content)
        {
            Encoding encode = Encoding.UTF8;
#if NET6_0 || NET7_0
            SHA1 sha1 =  SHA1.Create();
#else
            SHA1 sha1 = new SHA1CryptoServiceProvider();
#endif

            try
            {
                //创建SHA1对象
                byte[] bytes_in = encode.GetBytes(content);//将待加密字符串转为byte类型
                byte[] bytes_out = sha1.ComputeHash(bytes_in);//Hash运算               
                String result = BitConverter.ToString(bytes_out);//将运算结果转为string类型
                result = result.Replace("-", "").ToLower();
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                sha1.Clear();
            }
        }
    }
}
